<template>
    <div class="allocation-dialog-view">

        <el-dialog
                v-model="dialogShow"
                :close-on-click-modal="false"
                title="分配任务"
                width="900px"
                @closed="close"
        >

            <el-form
                    ref="refForm"
                    :model="formData"
                    :rules="rule"
                    class="demo-ruleForm"
                    label-width="120px"
            >
                <el-form-item label="招商产品信息">
                    <template v-if="datas">
                        <span>{{ getProductName(datas) }}</span>
                    </template>

                </el-form-item>

                <el-form-item v-if="objectData.planInfo.planType == 2" label="规划招商地区">
          <span>{{
              objectData.planDetail?.areaName ? objectData.planDetail?.cityName + "/" + objectData.planDetail?.areaName : objectData.planDetail?.cityName ? objectData.planDetail?.cityName : objectData.planDetail?.provinceName
            }}</span>
                </el-form-item>

                <el-form-item v-if="objectData.planInfo.planType == 1" label="招商终端">
                    <span>{{ objectData.planDetail?.terminalName }}</span>
                </el-form-item>

                <el-form-item v-if="objectData.planInfo.planType == 1" label="终端所在地区">
          <span>{{ objectData.planDetail?.terProvinceName }}/{{
              objectData.planDetail?.terCityName
            }}/{{ objectData.planDetail?.terAreaName }}</span>
                </el-form-item>

                <el-form-item label="跟进职员" prop="headId">
                    <el-select
                            v-model="formData.headId"
                            placeholder="请选择职员"
                            multiple
                            style="width: 100%"
                            @change="headChange"
                    >
                        <el-option
                                v-for="item in headOptions"
                                :key="item.id"
                                :label="item.realName"
                                :value="item.id"
                        />
                    </el-select>
                </el-form-item>

                <div style="display: flex;justify-content: space-between;margin-bottom: 10px">
                    <div>
                        <el-button class="main-btn" size="small" type="primary" @click="onAdd">增加行</el-button>
                        <el-button class="main-btn" size="small" type="primary" @click="onAgent">检索代理库添加</el-button>
                        <el-button class="border-btn" size="small" @click="onDate">设置相同开发跟进期限</el-button>
                    </div>

                    <div>
                        <span>未找到代理商</span>
                        <el-button style="margin: 0 10px" type="text" @click="onCreate">创建代理商</el-button>
                    </div>

                </div>

                <el-table :data="tableData" header-cell-class-name="table-header" border size="medium">
                    <el-table-column type="index"/>
                    <el-table-column
                            :show-overflow-tooltip="true"
                            align="left"
                            header-align="center"
                            label="代理名称"
                            prop="agentName"
                    >
                        <template #default="scope">
                            <el-autocomplete
                                    v-if="!scope.row.agentId"
                                    v-model="scope.row.agentName"
                                    :fetch-suggestions="querySearchAsyncAgent"
                                    placeholder="请输入代理商名称"
                                    style="width: 100%"
                                    @select="(val) => {handleSelectAgent(val,scope.$index)}"
                            >
                                <template #default="{ item }">
                                    <div v-if="item.agentType == 'agent'" class="distributeName">{{ item.agentName }}</div>
                                    <div v-else class="distributeName">{{ item.userName }}</div>
                                </template>
                            </el-autocomplete>

                            <dic v-else>
                                <el-popover
                                        v-if="scope.row.errorStr"
                                        :width="200"
                                        placement="top-start"
                                        trigger="hover"
                                >
                                    <span>{{ scope.row.errorStr }}</span>

                                    <template #reference>
                                        <el-icon style="margin: 0px 10px">
                                            <info-filled/>
                                        </el-icon>
                                    </template>
                                </el-popover>
                                <span>{{ scope.row.agentName }}</span>
                            </dic>
                        </template>
                    </el-table-column>
                    <el-table-column
                            :show-overflow-tooltip="true"
                            align="left"
                            header-align="center"
                            label="所在地区"
                    >
                        <template #default="{row}">
              <span v-if="row.id && row.agentType == 'agent'">{{ row.provinceName }}/{{ row.cityName }}/{{
                  row.areaName
                }}</span>
                            <span v-else-if="row.id">{{ row.address }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            :show-overflow-tooltip="true"
                            align="center"
                            header-align="center"
                            label="代理商状态"
                    >
                        <template #default="{row}">
                            <!--                            <span v-if="row.agentId && row.tradeStatus == 1">正式代理商</span>-->
                            <!--                            <span v-else-if="row.agentId">准代理商</span>-->
                            {{ getLabel('agent_status', row.agentStatus) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                            align="center"
                            header-align="center"
                            label="负责跟进职员"
                    >
                        <template #default="{row}">
                            <el-select
                                    v-if="row.isEdit"
                                    v-model="row.headId"
                                    placeholder="请选择职员"
                                    style="width: 100%"
                                    @change="rowHead(row)"
                            >
                                <el-option
                                        v-for="item in headList"
                                        :key="item.id"
                                        :label="item.realName"
                                        :value="item.id"
                                />
                            </el-select>

                            <span v-else>{{row.headName}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            :show-overflow-tooltip="true"
                            align="left"
                            header-align="center"
                            label="开发跟进期限"
                    >
                        <template #default="{row}">
                            <date-picker
                                    v-if="row.isEdit"
                                    v-model:date="row.dealTime"
                                    :disabled-date="disabledDate"
                                    placeholder="请选择跟进开发期限"
                                    style="width: 100%"
                            />
                            <span v-else-if="row.dealTime">{{ dateFormat('yyyy-mm-dd', row.dealTime) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            align="left"
                            header-align="center"
                            label="操作"
                            width="130px"
                    >
                        <template #default="scope">
                            <el-button v-if="!scope.row.isEdit" type="text" @click="onEdit(scope.row)">编辑</el-button>
                            <el-button v-else type="text" @click="onEnd(scope.row)">完成</el-button>
                            <el-button type="text" @click="onRemove(scope.$index)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button
                            class="border-btn"
                            size="small"
                            @click="close"
                    >取消
                    </el-button>
                    <el-button
                            class="main-btn"
                            size="small"
                            type="primary"
                            @click="confirm"
                    >确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog
                v-model="dateShow"
                :close-on-click-modal="false"
                width="400px"
                @closed="dateClose"
        >

            <el-form ref="dateForm" :model="formData" :rules="rule">
                <el-form-item label="开发跟进期限" prop="dealTime">
                    <date-picker
                            v-model:date="formData.dealTime"
                            :disabled-date="disabledDate"
                            placeholder="请选择跟进开发期限"
                            style="width: 100%"
                    />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button
                            class="border-btn"
                            size="small"
                            @click="dateClose"
                    >取消
                    </el-button>
                    <el-button
                            class="main-btn"
                            size="small"
                            type="primary"
                            @click="dateConfirm"
                    >确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <fromDialog ref="fromDialog"/>

        <detail-drawer
                ref="detailDrawer"
                :size-width="1000"
                custom-title
        >
            <template #title>
                <div style="display: flex;justify-content: space-between">
                    <span>检索代理库</span>

                    <el-button class="main-btn" size="small" type="primary" @click="agentConfirm">确定</el-button>
                </div>

            </template>
            <template #contents>

                <agentLibrary ref="agentLibrary" :datas="libraryData" :list="tableData" is-select/>

            </template>
        </detail-drawer>

    </div>

</template>

<script>
    import { InfoFilled } from '@element-plus/icons'
    import {crmStore} from "../../../../store";
    import {useRouter} from 'vue-router'
    import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, onMounted, reactive, toRefs} from 'vue'

    export default defineComponent({
        name: 'allocationDialog',
        emits: ['success'],
        components: {
            agentLibrary: defineAsyncComponent(
                () => import('./agentLibrary.vue')
            ),
            fromDialog: defineAsyncComponent(
                () => import('../../customer/modules/fromDialog.vue')
            ),
            InfoFilled,
        },
        setup(props, {emit}) {
            const router = useRouter()
            const currentInstance = getCurrentInstance()
            const api = inject('api')
            const rule = {
                agentName: [
                    {required: true, message: '请选择代理商', trigger: 'blur'}
                ],
                headId: [
                    {required: true, message: '请选择职员', trigger: 'blur'}
                ],
                dealTime: [
                    {
                        type: 'date',
                        required: true,
                        message: '请选择跟进开发期限',
                        trigger: 'change',
                    },
                ],
                headIds:[
                    {required: true, message: '请选择职员', trigger: 'blur'}
                ],
            }
            var data = reactive({
                dialogShow: false,
                dateShow: false,
                tableData: [],
                formData: {
                    saleTaskId:0,
                    planDetailId: 0, // 规划明细id
                    headId: '', // 跟进职员id
                    headName: '', // 跟进职员名称
                    productId: 0, // 产品id
                    headIds:[],
                },
                headOptions: crmStore.getters['company/getHeadOptions'],
                agents: [],
                datas: {},
                objectData:{},
                refForm: null,
                isNot: false,
                dateForm: null,
                libraryData: {},
                detailDrawer: null,
                agentLibrary: null,
                fromDialog: null,
                headList:[],
            })

            const onCreate = () => {
                data.fromDialog.open()
            }

            const onAdd = () => {
                data.tableData.push({isEdit: true,headId:'',errorStr:''})
            }

            const onRemove = (index) => {
                data.tableData.splice(index, 1)
            }

            const onEdit = (row) => {
                row.isEdit = true
            }

            const onEnd = (row) => {
                row.isEdit = false
            }

            const dateConfirm = () => {
                data.dateForm.validate((val) => {
                    if (val) {
                        data.tableData.forEach(item => {
                            item.dealTime = data.formData.dealTime
                        })
                        dateClose()
                    }
                })

            }

            const dateClose = () => {
                data.formData.dealTime = ''
                data.dateForm.clearValidate()
                data.dateShow = false
            }

            const onDate = () => {
                if (!data.tableData.length) {
                    currentInstance.proxy.customMessage({type: 'error', message: '请添加代理商'})
                    return;
                }
                data.dateShow = true
            }

            const onAgent = () => {
                data.detailDrawer.open()
            }

            const agentConfirm = () => {
                if (!data.agentLibrary.selects.length) {
                    currentInstance.proxy.customMessage({type: 'error', message: '请选择代理商'})
                    return
                }
                data.agentLibrary.selects.forEach(a => {
                    let item = {...a}
                    item.agentId = item.id
                    item.dealTime = ''
                    item.isEdit = false
                    if (!item.agentName) {
                        item.agentName = item.userName
                    }
                    data.tableData.push(item)
                })
                data.detailDrawer.close()
            }

            const getAgent = () => {
                const params = {
                    startTime: null,
                    endTime: null,
                    provinceCode: '',
                    cityCode: '',
                    areaCode: '',
                    tradeStatus: '',
                    from: '1',
                    pageSize: 100,
                    page: 1,
                    agentType: data.formData.radio
                }
                api.channelAgent.POTENTIALAGENT_LIST(params).then((res) => {
                    if (res.code === 0) {
                        data.agents = res.data.list || []
                    }
                })
            }

            const open = (item) => {
                data.datas = item
                data.formData.saleTaskId = item.id
                data.formData.productId = item.productId
                data.dialogShow = true

                data.libraryData.productId = item.productId
                data.objectData = JSON.parse(item.relationData)

                if (item.taskType == 1) {
                    console.log(data.objectData)
                    data.libraryData.from = '1'
                    data.libraryData.provinceCode = data.objectData.planDetail.provinceCode
                    data.libraryData.cityCode = data.objectData.planDetail.cityCode
                    data.libraryData.areaCode = data.objectData.planDetail.areaCode

                } else {
                    data.libraryData.from = '2'
                    data.libraryData.provinceCode = data.objectData.planDetail.terminalProvince
                    data.libraryData.cityCode = data.objectData.planDetail.terminalCity
                    data.libraryData.areaCode = data.objectData.planDetail.terminalArea
                    data.libraryData.terminalId = data.objectData.planDetail.terminalId
                }
            }

            const confirm = () => {
                data.refForm.validate((value) => {
                    if (value) {
                        // if (!data.tableData.length) {
                        //     currentInstance.proxy.customMessage({type: 'error', message: '请添加代理商'})
                        //     return
                        // }
                        for (let i = 0; i < data.tableData.length; i++) {
                            if (!data.tableData[i].id) {
                                currentInstance.proxy.customMessage({type: 'error', message: '请选择代理商'})
                                return;
                            }
                            if (data.tableData[i].errorStr) {
                                currentInstance.proxy.customMessage({
                                    type: 'error',
                                    message: data.tableData[i].errorStr
                                })
                                return;
                            }
                            if (!data.tableData[i].headId) {
                                currentInstance.proxy.customMessage({
                                    type: 'error',
                                    message: '请指定' + data.tableData[i].agentName + '的跟进职员'
                                })
                                return;
                            }
                            if (!data.tableData[i].dealTime) {
                                currentInstance.proxy.customMessage({
                                    type: 'error',
                                    message: '请选择' + data.tableData[i].agentName + '开发跟进期限'
                                })
                                return;
                            }
                        }
                        const a = {...data.formData}
                        a.planDetailId = Number(a.planDetailId)
                        a.productId = Number(a.productId)
                        a.allocationAgentInfo = data.tableData
                        a.saleTaskId = Number(a.saleTaskId)


                        api.plan.ALLOCATION_AGENT_CREATE(a).then(res => {
                            if (!res.code) {
                                currentInstance.proxy.customMessage({type: 'success', message: '分配成功'})
                                emit('success')
                                close()
                            } else {
                                currentInstance.proxy.customMessage({type: 'error', message: res.msg})
                            }
                        })
                    }
                })
            }

            const close = () => {
                data.formData = {
                    saleTaskId:0,
                    planDetailId: 0, // 规划明细id
                    agentId: '', // 分配的代理商id
                    agentName: '',
                    headId: '', // 跟进职员id
                    headName: '', // 跟进职员名称
                    dealTime: '', // 分配的跟进开发期限
                    productId: 0, // 产品id
                    radio: 'agent'
                }
                data.tableData = []
                data.isNot = false
                data.dialogShow = false
            }

            // 获取代理商列表
            const querySearchAsyncAgent = async (queryString, cb) => {
                const a = {
                    agentType: '',
                    keyWord: queryString,
                }
                let results = []
                const res = await api.editorial.EDITORIAL_KEYWORDS(a)
                if (!res.code && res.data) {
                    results = res.data.list || []
                    if ((!res.data.list || !res.data.list.length) && queryString) {
                        data.isNot = true
                    } else {
                        data.isNot = false
                    }
                }
                cb(results)
            }

            // 代理商事件
            const handleSelectAgent = (val, index) => {
                let x = data.tableData.findIndex(a => a.id == val.id)
                if (x != -1) {
                    currentInstance.proxy.customMessage({type: 'error', message: '代理商已添加'})
                    return
                }
                let a = {...val}
                a.agentId = a.id
                a.dealTime = data.tableData[index].dealTime
                a.headId = data.tableData[index].headId
                a.headName = data.tableData[index].headName
                a.isEdit = data.tableData[index].isEdit
                if (!a.agentName) {
                    a.agentName = a.userName
                }
                data.tableData[index] = a
                checkObject(index)
            }

            const checkObject = (index) => {
                let a = {
                    productId:data.datas.productId,
                    taskType:data.datas.taskType,
                    objectId:data.tableData[index].agentId
                }
                api.task.TASK_ALLOCATION_HEAD_CHECK(a).then(res=>{
                    if (!res.code){
                        data.tableData[index].errorStr = res.data
                    }else {
                        currentInstance.proxy.customMessage({type:'error',message:res.msg})
                    }
                })
            }

            const headChange = (val) => {
                data.headList = []
                data.formData.heads = []
                for (let i = 0; i < data.formData.headId.length; i++) {
                    const index = data.headOptions.findIndex(a => a.id == data.formData.headId[i])

                    if (index != -1){
                        data.headList.push(data.headOptions[index])
                        let heads = {
                            headId:data.headOptions[index].id,
                            headName:data.headOptions[index].realName
                        }
                        data.formData.heads.push(heads)
                    }
                }
                data.tableData.forEach(item=>{
                    if (item.headId){
                        const index1 = data.headList.findIndex(a => a.id == item.headId)
                        if (index1 == -1){
                            item.headId = ''
                            item.headName = ''
                        }
                    }else {
                        item.headId = ''
                        item.headName = ''
                    }
                })
            }

            const rowHead = (row) => {
                const index = data.headList.findIndex(a => a.id == row.headId)
                if (index != -1) {
                    row.headName = data.headList[index].realName
                }
            }

            const disabledDate = (time) => {
                return !(time.getTime() > Date.now())
            }

            onMounted(() => {
                getAgent()
            })

            return {
                ...toRefs(data),
                rule,

                confirm,
                close,
                open,
                disabledDate,
                headChange,
                querySearchAsyncAgent,
                handleSelectAgent,
                onCreate,
                onAdd,
                onEdit,
                onEnd,
                dateConfirm,
                dateClose,
                onDate,
                onAgent,
                agentConfirm,
                onRemove,
                rowHead,
            }
        }
    })
</script>

<style scoped>

</style>
